package com.auth.config.handler;

import com.auth.config.exception.AuthException;
import com.auth.config.exception.ConfigException;
import com.auth.config.exception.HttpRequestException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.utility.result.Result;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义失败异常
 * @author: hw
 * @date: 2021/11/23 17:55
 */
public class AuthFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        /**
         * 认证异常类型
         *  返回异常码 501
         */
        Result result = Result.returnCodeSuccess();
         if (exception instanceof HttpRequestException){
             result = Result.returnCode(-1, exception.getMessage());
        }
         else if (exception instanceof AuthException){
             result = Result.returnCode(-1, exception.getMessage());

         }
         else if (exception instanceof ConfigException){
             result = Result.returnCode(-1, exception.getMessage());
         }else if (exception instanceof InternalAuthenticationServiceException){
             result = Result.returnCode(-1, exception.getMessage());
         }

        ObjectMapper om = new ObjectMapper();
        String s = om.writeValueAsString(result);
        response.getWriter().write(s);
    }
}
